<?php

namespace Trawind\Basics\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class Unique implements Rule
{

    private $object;
    private $tabel;
    private $attribute;
    /**
     * Create a new rule instance.
     *
     * Unique constructor.
     * @param $tabel
     */
    public function __construct($object, $tabel)
    {
        $this->object = $object;
        $this->tabel = $tabel;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->attribute = $attribute;
        $data = explode(".", $attribute);
        if (isset($this->object->get($data[0])[$data[1]]['id'])) {
            $hasData = DB::table($this->tabel)
                ->where($data[2], $value)
                ->where('id', '<>', $this->object->get($data[0])[$data[1]]['id'])
                ->first();
        } else {
            $hasData = DB::table($this->tabel)
                ->where($data[2], $value)
                ->first();
        }

        if ($hasData) {
            return false;
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return __('validation.unique', ['attribute' => __('validation.attributes.'.$this->attribute)]);
    }
}
